package setup

import (
	"fmt"
	"log"
	"net/http"

	"douyin/repository/mysql"
	"douyin/routes"
	"douyin/setup/logger"
	"douyin/setup/settings"
	"douyin/utils/pkg/snowflake"
	"douyin/utils/pkg/validator"

	"go.uber.org/zap"
)

var Srv *http.Server

func Init() error {
	// 1. 加载配置
	if err := settings.Init(); err != nil {
		fmt.Printf("init settings failed, err:%v\n", err)
		return err
	}
	zap.L().Debug("settings init success...")
	//2. 初始化日志
	if err := logger.Init(settings.Conf.LogConfig, settings.Conf.Mode); err != nil {
		fmt.Printf("init logger failed, err:%v\n", err)
		return err
	}
	defer zap.L().Sync()
	zap.L().Debug("logger init success...")
	// 3. 初始化MySQL连接
	if err := mysql.Init(settings.Conf.MySQLConfig); err != nil {
		fmt.Printf("init mysql failed, err:%v\n", err)
		return err
	}
	// 4. 初始化雪花算法ID全局
	if err := snowflake.Init(settings.Conf.StartTime, settings.Conf.MachineID); err != nil {
		fmt.Printf("init snowflake failed, err:%v\n", err)
		return err
	}
	// 5. 初始化gin框架内置的校验器使用的翻译器
	if err := validator.InitTrans("zh"); err != nil {
		fmt.Printf("init validator trans failed, err:%v\n", err)
		return err
	}
	// 6. 注册路由
	r := routes.SetupRouter(settings.Conf.Mode)
	// 7. 启动服务
	Srv = &http.Server{
		Addr:    fmt.Sprintf(":%d", settings.Conf.Port),
		Handler: r,
	}
	go func() {
		// 开启一个goroutine启动服务
		if err := Srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	return nil
}
